# -*- coding: utf-8 -*-
# @File:     process_generate_progress.py
# @Author:
# @DateTime: 2025/06/10/16:45
import asyncio
import traceback

from app.api.generate.utils.redis_utils import key_remove_order_queue, update_task_state
from app.db.session import SessionLocal
from app.models.generate import GenerateTask, GenerateRecord


def process_generate_progress(message_data):
    # print(message_data)
    task_id = message_data.get('task_id')
    resp = message_data.get('resp', {})
    order_queue = resp.get('order_queue')
    db = SessionLocal()
    try:
        instance = db.query(GenerateTask).filter(GenerateTask.id == task_id, GenerateTask.state == 1).first()
        if instance:
            asyncio.run(update_task_state(task_id, 2, []))
            instance.state = 2
            db.add(instance)
            db.commit()
            db.refresh(instance)

        record = db.query(GenerateRecord).filter(GenerateRecord.g_task_id == task_id if instance else None, GenerateRecord.state == 1).first()
        if record:
            record.state = 2
            db.add(record)
            db.commit()
            db.refresh(record)
        if order_queue:

            # loop = asyncio.new_event_loop()
            # asyncio.set_event_loop(loop)
            # result = loop.run_until_complete(key_remove_order_queue(order_queue, task_id))
            # loop.close()
            asyncio.run(key_remove_order_queue(order_queue, task_id))
    except:
        print(traceback.format_exc())
    finally:
        db.close()
